<template>
	<view class="page-body">
		<!-- #ifdef APP-PLUS -->
		<view class="status_bar"> 
			<view class="top_view"></view> 
		</view> 
		<!-- #endif -->
		<tabbar currentText="线索">
			<!-- 头部导航 -->
			<view class="header">
				<view class="left_box" >
					<!--  @click="goBack()" -->
					<!-- <image class="left_icon" mode="widthFix" src="@/static/images/leftMark_icon.png"></image> -->
				</view>
				<view class="title">线索</view>
				<view class="right_box"  v-if="userInfo.role=='150' && Object.keys(btnPowerArr).includes(onlyClueBtnPower) "  @click="newclue">新建线索</view>
				<view class="right_box" v-else></view>
			</view>
			<!-- 导航 -->
			<view class="navBox">
				<searchInput @inputSearch="inputSearch" />
				<u-dropdown ref="uDropdown"  menu-icon-size='20' :style="{'--windowHeight':windowHeight}" :class="openShow?'udropdowns2':'udropdowns1'" title-size='26' @close="closeFun" @open="openFun">
						<u-dropdown-item  class='udd' height='640'  v-for="(item,idx) in screenArr" :key="idx" :height='idx==2?740:660' v-model="screenArr[idx].value" :title="item.label" :options="item.valList" @change="dropdownChangeFun($event,idx,item.valList)">
							<view class="slot-content" v-if="idx==0" style="background-color: #FFFFFF; min-height: 100vh;">
								<clueListIndex v-if="idx==0" :scHistoryList.sync='scHistoryList'></clueListIndex>
							</view>
							<view class="slot-content" v-if="idx==3" style="background-color: #FFFFFF;zInde:9999">
								<subsecTion :scHistoryList.sync='scHistoryList'></subsecTion>
							</view>
						</u-dropdown-item>
				</u-dropdown>

			</view>
			<!-- 历史记录 -->
			<view class="sehistory" v-if="scHistoryList.length" :style="{zIndex:openShow? 996:1086}">
					<view class="sehistory_list">
							<view class="sehistory_list_item" v-for="(scitem,scidx) in scHistoryList" :key='scidx'>
								{{scitem}}<u-icon name="close" color="#CCCCCC" size="16" style="margin-left: 10rpx;z-index: 79;top: -8rpx;" @click="clicksCisFun(scidx)"></u-icon>
							</view>			
					</view>
					<view class="emptysty" @click="clicksAllFun">
						清空
					</view>
			</view>

			<!-- 内容 -->

			<view class="content_box" :style="{marginTop:scHistoryList.length?'214rpx':'230rpx'}">
				<view class="list_ul" v-if="clueList.length">
					<block v-for="(item,idx) in clueList" :key="'a_'+ idx">
						<view class="list_li" @click="goDetails(item.id,item)" :style="idx==0 && scHistoryList.length?'marginTop:60rpx':''">							
							<view class="ou_li" >
								<image class="levelImg" v-if="item.intentionLevel"  :src="require('@/static/images/levelnew_'+ item.intentionLevel +'.png')"></image>
								<view class="left_box">
									<view class="info_box" :style="item.intentionLevel?'':'margin-left:26rpx'">
										<view class="info_name">
											<view style="color: #43425D;font-size: 32rpx;font-weight: 600;">
												{{item.customerName}}1
											</view>
											<view class="stateLabel" :style="stateLabelData[item.clueStatus]">{{item.clueStatus}}</view>
										 </view>
										<view class="info_time" v-if="item.clueStatus == '新建'">创建时间：{{item.createTime | dataFormat }}</view>
										<view class="info_time" v-else-if="item.clueStatus == '已派发'">派发时间：{{item.distributeTime | dataFormat }}</view>
										<view class="info_time" v-else>分配时间：{{item.assignTime | dataFormat }}</view>
										<view class="frequency">
											<image style="width: 22rpx;height: 22rpx;margin-right: 10rpx;" v-if="item.cleanResult" src="@/static/images/clean.png"></image>
											<view style="font-size: 22rpx;">{{item.cleanResult?'已清洗':''}}</view>
										</view>
									</view>							
								</view>
							</view>
							
							<view class="ou_li" v-if="item.intentCarBrand && item.intentCarModel && item.intentCarStyle">
								<image class="iconImg" src="@/static/images/model_icon.png"></image>
								<view class="">{{item.intentCarModel}}/{{item.intentCarStyle}}</view>
							</view>
							<view class="ou_li" v-else-if="item.intentCarBrand && item.intentCarModel">
								<image class="iconImg" src="@/static/images/model_icon.png"></image>
								<view class="">{{item.intentCarBrand}}/{{item.intentCarModel}}</view>
							</view>
							<view class="ou_li" v-else-if="item.intentCarStyle">
								<image class="iconImg" src="@/static/images/model_icon.png"></image>
								
							</view>						

							
							<view class="ou_li last_li" v-if="item.firstChannelName && item.secondChannelName">
								<image class="iconImg" src="@/static/images/channel_icon.png"></image>
								<view class="">{{item.firstChannelName}}/{{item.secondChannelName}}</view>
							</view>

							<view class="manualCleaning" v-if="item.cleanResult != null">
								<image src="@/static/images/manualCleaning.png"></image>
							</view>
							
							<view class="ou_li">
								<image class="iconImg" src="@/static/images/reportForm_icon.png"></image>
								<view style="display: flex;">跟进<text>{{item.followNum || 0}}</text>次 <u-line color="#43425D" length='25' margin="auto 16rpx" direction='col' />  到店<text>{{item.shopNum || 0}}</text>次</view>								
							</view>
							<view class="ou_li last_li" v-if="item.clueStatus != '已派发' && item.salesmanName && userInfo.role=='148'">
								<image class="iconImg" src="@/static/images/usericon.png"></image>
								<view class="">{{item.salesmanName}}</view>
							</view>

							<view class="operationBox" v-if="userInfo.role!='148'">
								<view class="btn" @click.stop="showOperation('phone', item)">
									<image class="iconImg" src="@/static/images/dadianhua.png"></image>打电话
								</view>
								<u-line color="#F0F0F7" direction="col" length='36' margin="auto"/>
								<view class="btn" @click.stop="showOperation('sms', item)">
									<image class="iconImg" src="@/static/images/duanxin.png"></image>发短信
								</view>
								<u-line color="#F0F0F7" direction="col" length='36' margin="auto"/>
								<view class="btn" @click.stop="showOperation('toxiansuo', item)">
									<image class="iconImg" src="@/static/images/xiansuo.png"></image>线索跟进
								</view>
									<!--<view class="btn" @click.stop="showOperation('outside_shop', item)">
									<image class="iconImg" src="@/static/images/meet2_img.png"></image>店外会面</view> -->
							</view>
						</view>
					</block>
				</view>
				<view class="list_ul" v-else>		
					<image style="width: 280rpx;height: 280rpx;margin-top: 100px;margin-left: calc(50% - 140rpx);"  src="@/static/images/nohistory.png"></image>
					<view style="text-align: center;margin-top: 40rpx;">
						暂无数据
					</view>					
				</view>
			</view>

		</tabbar>
		<show-modal v-if="isShowModal" :showType="showType" :isPopup="isShowModal" :popUpContent="popUpContent"  :showModalOperation.sync="isShowModal"/>
	</view>
</template>

<script>
	import clueDrawer from "../../components/clueDrawer.vue"
	import clueListIndex from "../../components/clueListIndex.vue"
	import subsecTion from "../../components/subsecTion.vue"
	import searchInput from "@/components/searchInput/index.vue";
	import tabbar from "@/components/tabbar/tabbar.vue";
	import showModal from "@/components/showModal/index.vue";
	import helper from '@/common/helper.js' //静态变量
	import {
		getClueList
	} from '@/service/api/api.js';
	import {
		parseTime
	} from "@/common/util.js"
	export default {
		components: {
			clueDrawer,
			searchInput,
			tabbar,
			showModal,
			clueListIndex,
			subsecTion
		},
		data() {
			return {
				stateLabelData:{
					'已分配':{
						background: '#DBE5FC',
						color: '#3788F7'
					},
					'新建':{
						background: '#D7F5EB',
						color: '#2BC992'
					},
					'战败/流失':{
						background: '#EBECF0',
						color: '#7B7B7B'
					},
					'无效':{
						background: '#EBECF0',
						color: '#7B7B7B'
					},
					'已派发':{
						background: '#EFDBFC',
						color: '#A75BD6'
					},
					'已到店':{
						background: '#FCDBE4',
						color: '#EA798B'
					},
					'已跟进':{
						background: '#DBF2F9',
						color: '#1CACDD'
					},
					'已成交':{
						background: '#F9EDDB',
						color: '#F8891B'
					},
					'已试驾':{
						background: '#FCEDDB',
						color: '#F8BA12'
					},
					'已下订':{
						background: '#FCDBDB',
						color: '#F46D6D'
					},
					'已交车':{
						background: '#DBF0E5',
						color: '#22B169'
					},
				
				
				},
				userInfo: {},
				btnPowerArr: {},
				onlyClueBtnPower: helper.onlyClueBtnPower,
				isUserRole:true,//控制新建权限
				// isUserRoleArr:[143,144,129,130,131,132,155,148],//没有权限的id
				listQuery: {
					pageNum: 1,
					pageSize: 10,
					deptId: '',
					roleType: '', //角色：1-销售经理；2
					searchKey: '',
					intentionLevel: '',
					clueStatus: '',
				},
				changeIntentionCar:{},
				clueDrawerForm: {
					cleanStatus: '',
					salesmanIds: '',
					intentCarModels: '',
					intentCarStyles: [],
					firstChannelIds: '',
					secondChannelIds: '',
					channelName: '', //渠道名称
					createStartTime: '',
					createEndTime: '',
					distributeStartTime: '',
					distributeEndTime: '',
					assignStartTime: '',
					assignEndTime: ''
				},
				clueList: [],
				scHistoryList:[],
				total: 0,
				screenArr: [
				{
					label: '意向车型',
					value:'',
					valList: []
					// ['车系&车型', '车型']
				},
				{
					label: '意向级别',
					value:'',
					valList: [
						{label: '全部',value:''},
						{label: 'O',value:'O'},
						{label: 'H',value:'H'},
						{label: 'A',value:'A'},
						{label: 'B',value:'B'},
						{label: 'C',value:'C'},
					]
				}, 
				{
					label: '线索状态',
					value:'',
					valList: [
					{
						label: '全部',
						value: '',
					}, {
						label: '新建',
						value: 'new',
					}, {
						label: '已派发',
						value: 'distributed',
					}, {
						label: '已分配',
						value: 'assigned',
					}, {
						label: '已跟进',
						value: 'followed',
					}, {
						label: '已到店',
						value: 'arrived',
					}, {
						label: '已试驾',
						value: 'driven',
					}, {
						label: '已下订',
						value: 'ordered',
					}, {
						label: '已成交',
						value: 'deal',
					}, {
						label: '已交车',
						value: 'delivery',
					}, {
						label: '战败/流失',
						value: 'defeated',
					}, {
						label: '无效',
						value: 'invalid',
					},
					],
				},
				{
					label: '更多条件',
					value:'',
					valList: []
				},

				],
				windowHeight:'',
				openShow:false,
				visible: false,
				isShowModal: false,
				showType:"call",
				popUpContent: {},
				ifOnShow: false,
				
			}
		},
		filters: {
			dataFormat(val) {
				return parseTime(val, '{m}-{d} {h}:{i}')
			}
		},
		computed:{
		},
		watch:{

		},
		onUnload() {
		
		},
		created() {
			uni.getSystemInfo({
			    success:  (res)=> {
					this.windowHeight=res.windowHeight
			    }
			});
			
		},
		
		onLoad() {
			try {
				this.userInfo = uni.getStorageSync('user_info') || {}
				this.btnPowerArr = uni.getStorageSync('btnPowerArr') || {}
				// console.log(this.userInfo)
			} catch (e) {
				console.log(e)
			}
			// this.init()
		},
		onShow() {
			this.clueList=[]
			if(this.ifOnShow) {
				this.init()
				this.ifOnShow = false
			}
			
			
			this.getStorageFun()
			this.resetFun()
			this.reqClueList()
		},
		onReachBottom() {
			if (this.total > this.clueList.length) {
				this.listQuery.pageNum += 1;
				this.reqClueList()
			}
		},
		mounted() {
			
		},
		methods: {
			init() {
				this.handleFilter()
				// this.isUserRoleFun()
			},
			// isUserRoleFun(){				
			// 	this.isUserRole=!this.isUserRoleArr.includes(this.userInfo.role)
			// 	console.log(this.userInfo.role,this.isUserRoleArr.includes(this.userInfo.role),"------------有无新建权限")
				
			// },
			//下拉菜单 筛选
			dropdownChangeFun(e,index,labelList){
				switch (index){
					case 0:
						break;
					case 1:
						if(e) this.setStorageFun(e)						
						this.listQuery.intentionLevel = e
						break;
					case 2:
						var {label}= labelList.find(a=>{return a.value==e}) 
						if(e) this.setStorageFun(label)
						this.listQuery.clueStatus = e
						break;
					case 3:
						this.$store.commit('changeTabIndex',998)
						break;
				}
				
				this.handleFilter()
				
			},
			closeFun(e){
				this.openShow=false
				if(e==3){
					this.$store.commit('changeTabIndex',999)
				}
			},
			openFun(e){
				this.openShow=true
				if(e==3){
					this.$store.commit('changeTabIndex',998)
				}
			},
			//意向车型 弹出框 关闭
			//tabi 
			//1 意向车型
			//4 更多条件
			closeDropdown(data,tabi) {
				// console.log(data,tabi,'意向车型 更多条件 弹出框 关闭')
				if(tabi==1 && data!='') {
					this.clueDrawerForm.intentCarStyles=data.intentCarStyle
				}
				if(tabi==4 && data!=''){
					if(typeof data === 'object' && data !== null){
						for (let key in data) {
							this.clueDrawerForm[key]=data[key]
						}
					}
				}
				
				this.clueList = []
				this.reqClueList()
			    this.$refs.uDropdown.close();
			},

			newclue(){
				uni.navigateTo({
					url:'/pages/clue/adviser/newClue/index'
				})
			},

			inputSearch(val) {

				this.listQuery.searchKey = val.trim()
				this.handleFilter()
			},

			handleFilter() {
				this.clueList = []
				this.listQuery.pageNum = 1;
				this.reqClueList()
			},

			async reqClueList() {
				let data = Object.assign(this.listQuery, this.clueDrawerForm)
				let newData = {}
				for (let key in data) {
					if (data[key] && data[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
						if (key == 'createStartTime' || key == 'createEndTime' || key == 'distributeStartTime' || key ==
							'distributeEndTime' || key == 'assignStartTime' || key == 'assignEndTime') {
							newData[key] = data[key].replace(/-/g,  "/") + ' 00:00:00'
						} else {
							newData[key] = data[key]
						}
					}
				}
				let res=await getClueList({
					...newData,
					userId: this.userInfo.userId,
					roleType: this.userInfo.role
				})
				if (res.data.code == 0) {
					if(this.listQuery.searchKey){
						
						this.scHistoryList.push(this.listQuery.searchKey)
						this.scHistoryList=Array.from(new Set(this.scHistoryList))
						
					}
					
					this.clueList = this.clueList.concat(res.data.data.content)
				//	console.log(this.clueList,'-----clueList 线索数据')
					this.total = res.data.data.totalElements
				} else {

				}
				// this.resetFun()			
			},
			//历史记录本地储存
			setStorageFun(data){
				this.scHistoryList.push(data)
				this.scHistoryList=Array.from(new Set(this.scHistoryList))
				uni.setStorage({
					key:'scHistoryList',
					data:JSON.stringify(this.scHistoryList),						
				})
			},
			//获取本地存储
			getStorageFun(){
				
				this.scHistoryList=uni.getStorageSync('scHistoryList')?JSON.parse(uni.getStorageSync('scHistoryList')) : []
				
			},
			
			actionSheetTap(idx) {
				let screenArr = this.screenArr[idx]
				if (idx == 0) {
					uni.navigateTo({
						url: '/pages/clue/series/index'
					})
				} else {
					uni.showActionSheet({
						itemList: screenArr.valList,
						success: (e) => {
							if (idx == '1') {
								this.listQuery.intentionLevel = e.tapIndex =='0' ? '' : screenArr.valList[e.tapIndex]
							}
							this.handleFilter()
						}
					})
				}
			},
			
			showModalOperation(type) {
				this.isShowModal = false
				
				if(type == '1') {
					
				} else if(type == '2') {
					this.connectByPhone()
				}
			},
			//点击历史 X
			clicksCisFun(idx){
				this.clueList = []
				let scHistory=this.scHistoryList[idx]
				// console.log(this.screenArr,'-----------this.scHistoryList[idx]',this.listQuery)
					this.screenArr[2].valList.forEach(v=>{
						if(v.label==scHistory){	
							scHistory=v.value
						}
					})
				let listQueryKeys=Object.keys(this.listQuery)[Object.values(this.listQuery).indexOf(scHistory)]
				this.listQuery[listQueryKeys]=''	
				this.screenArr.map(v=>{
						v.value=''
					return v
				})
				this.scHistoryList.splice(idx,1)
				if(!this.scHistoryList.length){
					this.resetFun()
					this.reqClueList()
				}
				uni.setStorage({
					key:'scHistoryList',
					data:JSON.stringify(this.scHistoryList),						
				})
				
				this.reqClueList()
			},
			//清空历史
			clicksAllFun(){
				this.scHistoryList.length=0
				this.clueList = []
				this.screenArr.map(v=>{
					v.value=''
					return v
				})
				this.resetFun()
				if(!this.scHistoryList.length){
					this.reqClueList()
				}
				uni.setStorage({
					key:'scHistoryList',
					data:JSON.stringify(this.scHistoryList),						
				})
				this.reqClueList()
				// this.resetFun()
			},
			//拨打电话 发短信 其他跳转
			showOperation(e, val){
				console.log(val,'拨打电话 发短信 其他跳转')
				switch (e){
					case 'phone':	
						this.popUpContent = {
							id:val.id,
							uniqueId: val.uniqueId,
							mobile: val.mobile,
							followNum: val.invalidNum || 0,
							clueStatus: val.clueStatus,
							isEdit:true
						}
						this.showType='phone'
						this.isShowModal=true
						break;
					case 'sms':
						this.showType='sms'
						this.popUpContent = {
							id:val.id,
							uniqueId: val.uniqueId,
							mobile: val.mobile,
							followNum: val.invalidNum || 0,
							clueStatus: val.clueStatus,
							isEdit:true
							
						}
						this.isShowModal=true
						break;
					case 'come_shop':
						uni.navigateTo({
							// id 跟进id, uniqueId 唯一id, followUp 形式, followNum 跟进次数,followPurposes 目的
							url: `/pages/clue/clueFollowUp/index?uniqueId=${val.uniqueId}&followNum=${val.invalidNum || 0}&followUp=${e}&clueStatus=${val.clueStatus}`
						})
						break;
					case 'outside_shop':
						uni.navigateTo({
							// id 跟进id, uniqueId 唯一id, followUp 形式, followNum 跟进次数,followPurposes 目的
							url: `/pages/clue/clueFollowUp/index?uniqueId=${val.uniqueId}&followNum=${val.invalidNum || 0}&followUp=${e}&clueStatus=${val.clueStatus}`
						})
						break;
					case 'toxiansuo':
						uni.navigateTo({
							// id 跟进id, uniqueId 唯一id, followUp 形式, followNum 跟进次数,followPurposes 目的
							url: `/pages/clue/clueFollowUp/index?uniqueId=${val.uniqueId}&followNum=${val.invalidNum || 0}&followUp=phone&clueStatus=${val.clueStatus}`
						})
						break;
					default:
						break;
				}
			},


			goDetails(id,item) {
				console.log(item,"-------------点击详情页面数据")
				uni.navigateTo({
					url: `/pages/clue/clueDetails/index?id=${item.id}&uniqueId=${item.uniqueId}&phone=${item.mobile}&followNum=${item.invalidNum || 0}&tabIdx=0&clueStatus=${item.clueStatus || 0}&customerName=${item.customerName}&firstChannelName=${item.firstChannelName}&secondChannelName=${item.secondChannelName}&intentCarBrand=${item.intentCarBrand}&intentCarModel=${item.intentCarModel}&intentCarStyle=${item.intentCarStyle}`
				})
			},
			//初始化数据
			resetFun(){
				this.clueDrawerForm= {
					cleanStatus: '',
					salesmanIds: '',
					intentCarModels: '',
					intentCarStyles: '',
					firstChannelIds: '',
					secondChannelIds: '',
					channelName: '', //渠道名称
					createStartTime: '',
					createEndTime: '',
					distributeStartTime: '',
					distributeEndTime: '',
					assignStartTime: '',
					assignEndTime: ''
				}
				this.listQuery= {
					pageNum: 1,
					pageSize: 10,
					deptId: '',
					roleType: '', //角色：1-销售经理；2
					searchKey: '',
					intentionLevel: '',
					clueStatus: '',
				}
			},
			goBack() { //返回上一层
				uni.navigateBack()
			}
		}
	}

</script>

<style scoped lang="scss">
	@import './index.scss';


	/deep/ .u-flex{
		display: flex;
	}

	.udropdowns1 /deep/ .u-dropdown__content{
		height: 0 !important;
	}
	// .udropdowns2 /deep/ .u-dropdown__content{
	// 	height: 651px !important;
	// }
	

</style>
<style>
	/deep/.u-dropdown__content{
		// z-index: 999 !important;
		height: var(--windowHeight);
	}
</style>

